import Compressor from 'compressorjs';
/** 
 * 临时路径转换为file对象
 * file: 临时路径
 * */
export function tempFilePathToFile(file, quality = 0.5) {
    return new Promise((resolve, reject) => {
        // 将临时路径转为File对象
        uni.downloadFile({
            url: file,
            success: (downloadRes) => {
                // 创建一个临时的a标签来获取文件
                const link = document.createElement('a');
                link.href = downloadRes.tempFilePath;
                fetch(downloadRes.tempFilePath)
                    .then(response => response.blob())
                    .then(blob => {
                        const tempFilePath = new File([blob], 'image.jpg', {
                            type: blob.type
                        });
                        let filePath = compressImage(tempFilePath, quality)
                        resolve(filePath)
                    })
                    .catch(err => {
                        console.error('文件处理失败：', err);
                        uni.showToast({
                            title: '图片处理失败',
                            icon: 'none'
                        });
                    });
            }
        })
    })
}

/**
 * 封装图片压缩
 */
function compressImage(file, quality) {
    return new Promise((resolve, reject) => {
        new Compressor(file, {
            quality: quality,
            maxWidth: 1000,
            convertSize: 500000,
            success: (result) => {
                const reader = new FileReader();
                reader.onload = (e) => {
                    let compressedImage = e.target.result;
                    resolve(compressedImage)
                };
                reader.readAsDataURL(result);
            },
            error: (err) => {
                console.error('压缩失败：', err.message);
                uni.showToast({
                    title: '图片压缩失败',
                    icon: 'none'
                });
            }
        });
    })

}